package org.example.javachatroom.controller;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpSession;
import org.example.javachatroom.mapper.UserMapper;
import org.example.javachatroom.model.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class UserController {
    @Autowired
    private UserMapper userMapper;

    @PostMapping("/login")
    @ResponseBody
    public Object login(String username,String password,HttpServletRequest request){
        //1、去数据库中查找，看username能否找到对应的user对象
        //  如果能找到则看一下密码是否匹配
        User user = userMapper.selectByName(username);
        System.out.println("username:"+username+"   password:"+password);
        //这里把用户输入的password放在后边主要是为了防止空指针异常
        if(user == null||!user.getPassword().equals(password)){
            //这两条件具备一个，就是登录失败,返回一个空对象
            System.out.println("登录失败！用户名或密码错误！"+user);
            return new User();
        }
        //2、如果都匹配，登陆成功！！创建会话    true的意思：如果会话不存在则创建
        HttpSession session = request.getSession(true);
        session.setAttribute("user",user);
        //3、在返回之前，把密码干掉，避免返回不必要的信息
        user.setPassword("");
        return user;
    }

    @PostMapping("/register")
    @ResponseBody
    public Object register(String username,String password){
        User user = null;
        try {
            user = new User();
            user.setUsername(username);
            user.setPassword(password);
            int ret = userMapper.insert(user);
            System.out.println("注册 ret:"+ret);
            user.setPassword("");

        } catch (DuplicateKeyException e) {
          //如果抛出异常，说明名字重复了，说明名字重复了，注册失败
            user = new User();
            System.out.println("注册失败！！！，username:"+username);
        }
        return user;
    }

    @GetMapping("/userInfo")
    @ResponseBody
    public Object getUserInfo(HttpServletRequest request){
        //1、从请求中获取会话
        HttpSession session = request.getSession(false);
        if(session == null){
            //会话不存在，用户尚未登录，此时返回一个空对象
            System.out.println("[getUserinfo] 当前获取不到 session 对象");
            return new User();
        }
        //2、从会话中获取到之前保存的用户对象
        User user = (User) session.getAttribute("user");
        if(user == null){
            System.out.println("[getUserInfo] 当前获取不到user对象");
            return new User();
        }
        user.setPassword("");
        return user;
    }
}
